import { Request, Response } from 'express';
import { policyNewsService } from './service';
import { PolicyNewsType } from '../../entities/PolicyNews';

/**
 * 获取政策新闻列表 (APP接口)
 * 获取所有类型的政策新闻，支持分页，按发布时间升序排序
 * @route GET /api/app/policy/list
 */
export const getPolicyNews = async (req: Request, res: Response) => {
  try {
    const page = Number(req.query.page) || 1;
    const size = Number(req.query.size) || 10;
    
    // 构建查询参数，包含分页、激活状态和排序参数
    const queryParams: any = {
      page,
      pageSize: size,
      isActive: true, // 只获取激活的新闻
      // 指定按发布时间升序排序
      sortField: 'publishTime',
      sortOrder: 'ASC'
    };
    
    // 调用服务层查询方法
    const { news, total } = await policyNewsService.getPolicyNewsList(queryParams);
    
    // 简化返回数据结构，只包含前端需要的字段
    const simplifiedNews = news.map(item => ({
      id: item.id,
      title: item.title,
      type: item.type,
      publisher: item.publisher,
      publishTime: item.publishTime,
      linkUrl: item.linkUrl,
      // 如果有链接地址，则不返回内容
      content: item.linkUrl ? null : item.content
    }));
    
    res.json({
      success: true,
      data: {
        records: simplifiedNews,
        total,
        size,
        current: page,
        pages: Math.ceil(total / size)
      }
    });
  } catch (error: any) {
    res.json({
      success: false,
      message: error.message || '获取新闻列表失败'
    });
  }
};
/**
 * 获取政策新闻详情 (APP接口)
 * @route GET /api/app/policy/detail/:id
 */
export const getPolicyNewsDetailApp = async (req: Request, res: Response) => {
  try {
    const id = req.params.id;
    if (!id) {
      return res.json({
        success: false,
        message: '缺少新闻ID'
      });
    }
    
    const news = await policyNewsService.getPolicyNewsById(id);
    
    if (!news) {
      return res.json({
        success: false,
        message: '新闻不存在'
      });
    }
    
    // 确认是否处于激活状态
    if (!news.isActive) {
      return res.json({
        success: false,
        message: '新闻不存在或已下线'
      });
    }
    
    // 简化返回数据，只包含前端需要的字段
    const simplifiedNews = {
      id: news.id,
      title: news.title,
      type: news.type,
      content: news.content,
      linkUrl: news.linkUrl,
      publisher: news.publisher,
      publishTime: news.publishTime
    };
    
    res.json({
      success: true,
      data: simplifiedNews
    });
  } catch (error: any) {
    res.json({
      success: false,
      message: error.message || '获取新闻详情失败'
    });
  }
}; 